<template>
  <div id="groups">
    <div class="card">
      <div class="card-header bg-info text-white">组管理</div>
      <div class="card-body">
        <form class="row">
          <div class="col">
            <button
              type="button"
              class="btn btn-primary"
              @click.stop="search()"
            >
              查找
            </button>

            <span class="float-end">
              <a
                href="javascript:void(0)"
                @click.stop="newGroup()"
                class="btn btn-success"
                >新建</a
              >
            </span>
          </div>
        </form>
      </div>
      <table class="table table-striped table-sm">
        <thead>
          <tr>
            <th>组名</th>
            <th>角色</th>
            <th>用户</th>
            <th>创建日期</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(info, index) in dataList" :key="index">
            <td>{{ info.groupName }}</td>
            <td>
              <template v-if="info.authorities.length > 0">
                <span v-for="role in info.authorities"
                  >{{ role.roleName }}
                </span>
              </template>
              <template v-else> 无 </template>
              <a
                href="javascript:void(0)"
                class="small"
                @click.stop="editRole(index)"
                >编辑</a
              >
            </td>
            <td>
              <template v-if="info.users.length > 0">
                <span v-for="user in info.users">
                  <template v-if="user.userInfo !== null">
                    {{ user.userInfo.empname }}
                  </template>
                  <template v-else>, null</template>
                </span>
              </template>
              <template v-else> 无 </template>
              <a
                href="javascript:void(0)"
                class="small"
                @click.stop="editUser(info.id)"
                >编辑</a
              >
            </td>
            <td>{{ info.createTime }}</td>
          </tr>
        </tbody>
      </table>
      <nav id="pagination-box" class="float-end">
        <my-pagination
          name="pagination"
          :row-count="sc.rowCount"
          :page-total="sc.pageTotal"
          :page-no="sc.pageNo"
          @next-page="nextPage"
          @prev-page="prevPage"
          @direct-page="directPage"
        ></my-pagination>
      </nav>
    </div>

    <my-modal-group ref="groupModal"></my-modal-group>
    <my-modal-group-role
      ref="groupRoleModal"
      :roles="roles"
    ></my-modal-group-role>
    <my-modal-group-user
      ref="groupUserModal"
      :groupUsers="groupUsers"
      :excludedUsers="excludedUsers"
      @addUserToGroup="addUserToGroup"
      @delUserFromGroup="delUserFromGroup"
    ></my-modal-group-user>
  </div>
</template>

<script>
import $ from "jquery";
import MyPagination from "@/components/my-pagination.vue";
import {
  searchGroups,
  saveGroup,
  saveRole,
  addUserToGroup,
  delUserFromGroup,
  searchRoles,
} from "@/api/groups.js";
import { searchUsers2 } from "@/api/user.js";
import MyModalGroup from "@/components/modal/my-modal-group.vue";
import MyModalGroupRole from "@/components/modal/my-modal-group-role.vue";
import MyModalGroupUser from "@/components/modal/my-modal-group-user.vue";

export default {
  components: {
    MyPagination,
    MyModalGroup,
    MyModalGroupRole,
    MyModalGroupUser,
  },
  data() {
    return {
      sc: {
        rowCount: 0,
        pageNo: 1,
        pageSize: 15,
        pageTotal: 0,
      },

      dataList: [],
      groupName: "",
      roleSelected: [],
      id: 0,

      users: [],
      groupUsers: [],
      roles: [],
      userId: 0,
    };
  },
  computed: {
    excludedUsers: function () {
      let self = this;
      return this.users.filter(function (p) {
        let b = true;
        for (let rp of self.groupUsers) {
          if (rp.username === p.username) {
            b = false;
            break;
          }
        }

        return b;
      });
    },
  },
  mounted: function () {
    this.search();
    this.searchRoles();
  },
  methods: {
    showErrMsg: function (msg, msgType) {
      this.$store.dispatch("showAlertMsg", {
        errMsg: msg,
        errMsgType: msgType,
      });
    },
    search: function () {
      const params = {
        "sc.pageNo": this.sc.pageNo,
        "sc.pageSize": this.sc.pageSize,
      };

      searchGroups(params, (jsonResult) => {
        this.dataList = jsonResult.dataList;

        if (this.id > 0) {
          this.prepareToEditUser(this.id);
        }
      });
    },
    newGroup: function () {
      this.$refs.groupModal
        .modal()
        .then((v) => {
          this.saveGroup(v.groupId, v.groupName);
        })
        .catch();
    },
    saveGroup: function (id, groupName) {
      const params = {
        id,
        groupName,
      };

      saveGroup(params, (jsonResult) => {
        if (jsonResult.status === "OK") {
          this.showErrMsg("保存成功");
          this.search();
        } else {
          this.showErrMsg("保存失败：" + jsonResult.errMsg);
        }
      });
    },
    editRole: function (idx) {
      const info = this.dataList[idx];
      this.id = info.id;
      this.groupName = info.groupName;
      this.roleSelected.splice(0);

      for (let i = 0; i < info.authorities.length; i++) {
        this.roleSelected.push(info.authorities[i].role);
      }

      const params = {
        groupId: this.id,
        groupName: this.groupName,
        roleSelected: this.roleSelected,
      };

      this.$refs.groupRoleModal
        .modal(params)
        .then((v) => {
          this.saveRole(v);
        })
        .catch();
    },
    saveRole: function (v) {
      let roleName = "";
      for (let i = 0; i < v.roleSelected.length; i++) {
        roleName += v.roleSelected[i] + ",";
      }

      const params = {
        id: v.groupId,
        roleName: roleName,
      };

      saveRole(params, (jsonResult) => {
        if (jsonResult.status === "OK") {
          this.showErrMsg("保存成功");
          this.search();
        } else {
          this.showErrMsg("保存失败：" + jsonResult.errmsg);
        }
      });
    },
    editUser: function (id) {
      this.prepareToEditUser(id);

      this.$refs.groupUserModal.modal({ groupName: this.groupName });
      if (this.users.length === 0) {
        this.searchUsers();
      }
    },
    prepareToEditUser: function (id) {
      this.id = id;
      let info;
      for (let info0 of this.dataList) {
        if (info0.id === this.id) {
          info = info0;
          break;
        }
      }

      this.groupName = info.groupName;

      this.groupUsers.splice(0);
      for (let i = 0; i < info.users.length; i++) {
        if (info.users[i].userInfo === null) {
          continue;
        } else {
          // console.log(info.users[i])
        }
        this.groupUsers.push({
          id: info.users[i].userInfo.id,
          username: info.users[i].userInfo.username,
          name: info.users[i].userInfo.empname,
        });
      }
    },
    searchUsers: function () {
      const params = {
        "sc.pageNo": 1,
        "sc.pageSize": 1000,
        "sc.status": 1,
      };
      searchUsers2(params, (jsonResult) => {
        this.users = jsonResult.dataList;
      });
    },
    addUserToGroup: function (userId) {
      const params = {
        userId: userId,
        groupId: this.id,
      };

      addUserToGroup(params, (jsonResult) => {
        if (jsonResult.status === "OK") {
          this.showErrMsg("保存成功");
          // $('#modalUser').modal('hide')

          this.search();
        } else {
          this.showErrMsg("保存失败：" + jsonResult.errmsg);
        }
      });
    },
    delUserFromGroup: function (userId) {
      const params = {
        userId: userId,
        groupId: this.id,
      };

      delUserFromGroup(params, (jsonResult) => {
        if (jsonResult.status === "OK") {
          this.showErrMsg("删除成功");
          // $('#modalUser').modal('hide')

          this.search();
        } else {
          this.showErrMsg("删除失败：" + jsonResult.errmsg);
        }
      });
    },
    searchRoles: function () {
      searchRoles((jsonResult) => {
        this.roles = jsonResult;
      });
    },
    prevPage: function () {
      this.sc.pageNo = this.sc.pageNo - 1;
      if (this.sc.pageNo < 1) this.sc.pageNo = 1;
      this.search();
    },
    nextPage: function () {
      this.sc.pageNo = this.sc.pageNo + 1;
      this.search();
    },
    directPage: function (pageNo) {
      this.sc.pageNo = pageNo;
      this.search();
    },
  },
};
</script>
